package com.zy.springboot.controller.book;

import com.alibaba.fastjson.JSONObject;
import com.zy.springboot.com.*;
import com.zy.springboot.entity.user.UserEntity;
import com.zy.springboot.service.book.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by y on 2019/1/11.
 */
@Api(value = "book接口", description = "book接口")
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @ResponseBody
    @RequestMapping(value = "/getBookList.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "getBookList",
            notes = "getBookList ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{}", dataType = "String", paramType = "body")
    public void getUserList(HttpServletResponse response,  @RequestBody(required = false) String jsonData) {
        JSONObject records=bookService.getBookList(jsonData);
        if (null != records) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(records));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("查找失败"));
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getBookById.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "getBookById",
            notes = "getBookById ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{bookId:'1'}", dataType = "String", paramType = "body")
    public void getUserById(HttpServletResponse response,  @RequestBody String jsonData) {
        JSONObject result=bookService.getBookById(jsonData);
        if (null != result) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("查找失败"));
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getBookIndex.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "getBookIndex",
            notes = "getBookIndex ",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{}", dataType = "String", paramType = "body")
    public void getBookIndex(HttpServletResponse response,  @RequestBody String jsonData) throws IOException{
        JSONObject result=bookService.getBookIndex(jsonData);
        if (null != result) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("失败"));
        }
    }

    private static String getSubStr(String str, int num) {
        String result = "";
        int i = 0;
        while(i < num) {
            int lastFirst = str.lastIndexOf('/');
            result = str.substring(lastFirst) + result;
            str = str.substring(0, lastFirst);
            i++;
        }
        return result.substring(1);
    }
    @ResponseBody
    @RequestMapping(value = "/getOAuthTokenEntity.json", method = RequestMethod.GET)
    @ApiOperation(
            value = "getOAuthTokenEntity",
            notes = "getOAuthTokenEntity ",
            httpMethod = "GET",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{code:'1'}", dataType = "String", paramType = "body")
    public void getOAuthTokenEntity(HttpServletResponse response, HttpServletRequest request) {
        String code = request.getParameter("code");
        String avatarUrl = request.getParameter("avatarUrl");
        String city = request.getParameter("city");
        String province = request.getParameter("province");
        String country = request.getParameter("country");
        String gender = request.getParameter("gender");
        String nickName = request.getParameter("nickName");
        UserEntity userEntity=new UserEntity();
        userEntity.setAvatarUrl(avatarUrl);
        userEntity.setCity(city);
        userEntity.setProvince(province);
        userEntity.setCountry(country);
        userEntity.setSex(Integer.parseInt(gender));
        userEntity.setNickName(nickName);
        JSONObject result=bookService.getOAuthTokenEntity(code,userEntity);
        if (null != result) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("查找失败"));
        }
    }
    @RequestMapping(value = "/downloadOnlineLearnMaterials.json",method =RequestMethod.GET )
    public void downloadFile( HttpServletResponse response,@RequestParam String fileName) throws IOException {
        BufferedInputStream dis = null;
        BufferedOutputStream fos = null;
        String urlString = "https://www.yyyybook.club:80//"+ URLEncoder.encode(getSubStr(fileName,2), "UTF-8").replace("%2F","/");
        fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
        try {
            URL url = new URL(urlString);
            response.reset();//避免空行
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
               bis = new BufferedInputStream(url.openStream());
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");

         /* dis = new BufferedInputStream(url.openStream());
            fos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[1024];
            int bytesRead;
            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
                fos.write(buff, 0, bytesRead);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dis != null)
                dis.close();
            if (fos != null)
                fos.close();
        }
    }

    @RequestMapping(value = "/downloadOnlineLearnMaterials2.json",method =RequestMethod.GET )
    public void downloadFile2( HttpServletResponse response,@RequestParam String fileName) throws IOException {
       /* downloadUtil down2=new downloadUtil(response);
        down2.downFile("仙逆.txt");*/
        downloadFile(response,fileName);
    }

    @ResponseBody
    @RequestMapping(value = "/load.json", method = RequestMethod.GET)
    @ApiOperation(
            value = "load",
            notes = "load ",
            httpMethod = "GET",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{}", dataType = "String", paramType = "body")
    public void load(HttpServletRequest request, HttpServletResponse response) throws IOException{
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && SignUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

